package com.hk.dyeyuesystem;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.hk.dyeyuesystem.db.DBOpenHelper;
import com.hk.dyeyuesystem.util.DateUtil;
import com.hk.dyeyuesystem.util.RegexUtil;
import com.hk.dyeyuesystem.util.ToastUtil;

import java.util.Date;
import java.util.Objects;

/**
 * 注册相关操作控制层
 */
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener {

    //    Initialize Toast
    private Toast toast;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //    Initialize username account password
    private EditText username;
    private EditText account;
    private EditText password;
    //    确认密码
    private EditText password2;

    private Button goBackBtn, registerBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        //        实例化
        dbOpenHelper = new DBOpenHelper(RegisterActivity.this, "db_book_system", null, 1);
//        获取昵称、账号、密码的编辑框控制权
        username = findViewById(R.id.username);
        account = findViewById(R.id.account);
        password = findViewById(R.id.password);
        password2 = findViewById(R.id.password2);
//        设置离开焦点事件
        username.setOnFocusChangeListener(this);
        account.setOnFocusChangeListener(this);
        //        获取注册按钮并设置点击事件
        goBackBtn = findViewById(R.id.go_back_btn);
        registerBtn = findViewById(R.id.register_add_btn);
        goBackBtn.setOnClickListener(this);
        registerBtn.setOnClickListener(this);
    }

    /**
     * 点击事件处理
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register_add_btn:
//                校验账户并进行注册
                registerAccount();
                break;
            case R.id.go_back_btn:
//                关闭Activity
                finish();
                break;
        }

    }

    /**
     * 注册相关逻辑
     */
    private void registerAccount() {
//        获取昵称、账号、密码的内容
        String registerUserName = username.getText().toString();
        String registerAccount = account.getText().toString();
        String registerPassword = password.getText().toString();
        String registerPassword2 = password2.getText().toString();
//        验证注册昵称
        if (registerUserName.equals("") || registerUserName == null) {
            toast = ToastUtil.toastHint(toast, RegisterActivity.this, "昵称不能为空！");
            return;
        } else {
            Boolean isExistUserName = findByUserName(registerUserName);
            if (isExistUserName) {
                toast = ToastUtil.toastHint(toast, RegisterActivity.this, "该昵称已被使用，请更换！");
                return;
            }
        }
//        验证注册手机号
        if (RegexUtil.checkPhone(registerAccount)) {
            Boolean isExistPhone = findByAccount(registerAccount);
            if (isExistPhone) {
                toast = ToastUtil.toastHint(toast, RegisterActivity.this, "该手机号已经被注册，请更换手机号重试！");
                return;
            }
        } else {
            toast = ToastUtil.toastHint(toast, RegisterActivity.this, "请输入正确的手机号！");
            return;
        }
//        验证密码
        Boolean isExistPwd = checkPassword(registerPassword);
        if (!isExistPwd) {
            toast = ToastUtil.toastHint(toast, RegisterActivity.this, "密码长度不能少于6位,请重新输入！");
            return;
        }
        if (registerPassword.equals(registerPassword2)) {
            // TODO: 2021/12/11 开始新增注册用户（已完成）
            SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//            封装需要插入的值
            ContentValues contentValues = new ContentValues();
            contentValues.put("USERNAME",registerUserName);
            contentValues.put("ACCOUNT",registerAccount);
            contentValues.put("PASSWORD",registerPassword);
//            判断是否为管理员注册
            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                if (Objects.isNull(bundle)) {
                    contentValues.put("TYPE", 0);
                } else {
                    contentValues.put("TYPE",1);
                }
            }
            contentValues.put("CREATE_TIME", DateUtil.dateString(new Date()));
            contentValues.put("UPDATE_TIME", DateUtil.dateString(new Date()));
//            执行插入方法
            readableDatabase.insert("ACCOUNT",null,contentValues);
            toast = ToastUtil.toastHint(toast, RegisterActivity.this, "注册成功，请返回进行登录！");
            return;
        } else {
            toast = ToastUtil.toastHint(toast, RegisterActivity.this, "密码不一致,请重新输入！");
            return;
        }


    }

    /**
     * 焦点事件处理
     *
     * @param v
     * @param hasFocus fasle 离开焦点
     */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
//            昵称
            case R.id.username:
                if (hasFocus) break;
                /**
                 * 通过昵称查询是否被使用
                 */
                String userName = username.getText().toString();
                if (userName.equals("") || userName == null) {
                    toast = ToastUtil.toastHint(toast, RegisterActivity.this, "昵称不能为空！");
                    break;
                }
                Boolean isExistUserName = findByUserName(userName);
                if (isExistUserName) {
                    toast = ToastUtil.toastHint(toast, RegisterActivity.this, "该昵称已被使用，请更换！");
                    break;
                }
                break;
//             账户
            case R.id.account:
                if (hasFocus) break;
                String phone = account.getText().toString();
//                判断是否符合手机号标准
                if (RegexUtil.checkPhone(phone)) {
                    Boolean isExistPhone = findByAccount(phone);
                    if (isExistPhone) {
                        toast = ToastUtil.toastHint(toast, RegisterActivity.this, "该手机号已经被注册，请更换手机号重试！");
                    }
                    break;
                }
                toast = ToastUtil.toastHint(toast, RegisterActivity.this, "请输入正确的手机号！");
                break;
//                验证密码
            case R.id.password:
                String pwdToString = password.getText().toString();
                /**
                 * 验证密码是否符合规则
                 */
                Boolean isExistPwd = checkPassword(pwdToString);
                if (isExistPwd) break;
                toast = ToastUtil.toastHint(toast, RegisterActivity.this, "密码长度不能少于6位,请重新输入！");
                break;
            default:
                break;
        }
    }

    /**
     * 校验密码是否小于6位数
     * @param pwdToString
     * @return
     */
    private Boolean checkPassword(String pwdToString) {
        if (pwdToString.length() < 6) {
            return false;
        }
        return true;
    }

    /**
     * 通过输入手机号验证该手机号是否被
     *
     * @param phone 手机号码
     * @return
     */
    private Boolean findByAccount(String phone) {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("ACCOUNT", null, "ACCOUNT = ?", new String[]{phone}, null, null, null);
        // 判断该手机号是否已被注册
        if (cursor.moveToNext()) {
            return true;
        }
        return false;
    }

    /**
     * 通过昵称查询该昵称是否被使用
     *
     * @param userName 注册用户昵称
     * @return
     */
    private Boolean findByUserName(String userName) {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("ACCOUNT", null, "USERNAME = ?", new String[]{userName}, null, null, null);
        // 判断该昵称是否已被使用
        if (cursor.moveToNext()) {
            return true;
        }
        return false;
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}